package com.lam.schedule.common.scheduler.model;

import java.util.Map;

import org.quartz.Job;
import org.quartz.JobDataMap;
import org.quartz.JobExecutionContext;
import org.quartz.SchedulerException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.lam.common.exception.BaseException;
import com.lam.common.utils.JsonUtil;
import com.lam.schedule.common.constant.ScheduleConstant;
import com.lam.schedule.entity.ScheduleJob;
import com.lam.schedule.entity.ScheduleJobLog;

public abstract class AbstractQuartzJob extends AsyncJob implements Job {
	
	protected final Logger logger = LoggerFactory.getLogger(this.getClass());
	
	@Override
	public void execute(JobExecutionContext context) {
		try {
			JobDataMap jobDataMap = context.getMergedJobDataMap();
			ScheduleJob scheduleJob = (ScheduleJob) jobDataMap.get(ScheduleConstant.JOB_DATA_KEY);
			Map<String, Object> exeParam = JsonUtil.parseJSON(jobDataMap.get(ScheduleConstant.JOB_PARAM_KEY));
			ScheduleJobLog jobLog = getJobLog(scheduleJob, exeParam);
			String instanceName = context.getScheduler().getSchedulerInstanceId();
			jobLog.setSchedName(context.getScheduler().getSchedulerName());
			jobLog.setInstanceName(instanceName);
			String[] ss = instanceName.split("-");
			jobLog.setInstanceIp(ss[0]);
			if(ss.length>1) {
				jobLog.setInstanceId(ss[1]);
			}
			runJob(scheduleJob, exeParam, jobLog);
		} catch (SchedulerException e) {
			throw new BaseException("调度任务执行异常", e);
		}
	}

}
